import React, { useState, useEffect } from 'react';
import { message, Space, Popconfirm, Checkbox } from 'antd';
import { Button } from '@/components/eai-design';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Search } from '@/components/eai-design';
import Tables from '@/components/tables/tables';
import Modals from '@/components/modals/Modals';
import nl2sqlService from '@/api/services/nl2sqlService';
import { TermInfo } from '@/types/nl2sql/type';

interface TerminologyManagementProps {
  knowledgeId: string;
}

const TerminologyManagement: React.FC<TerminologyManagementProps> = ({ knowledgeId }) => {
  const [searchValue, setSearchValue] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingTerm, setEditingTerm] = useState<TermInfo | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
  });

  // 获取术语列表
  const { data: terms = [], loading, refresh } = useRequest(
    () => nl2sqlService.getTerms(knowledgeId),
    {
      refreshDeps: [knowledgeId],
    }
  );

  // 创建术语
  const { runAsync: createTerm, loading: createLoading } = useRequest(
    (data: { knowledge_id: string; name: string; description: string }) =>
      nl2sqlService.createTerm(data),
    {
      manual: true,
      onSuccess: () => {
        message.success('创建术语成功');
        setIsModalVisible(false);
        resetForm();
        refresh();
      },
      onError: (error) => {
        message.error('创建术语失败');
        console.error('创建术语失败:', error);
      },
    }
  );

  // 更新术语
  const { runAsync: updateTerm, loading: updateLoading } = useRequest(
    (data: { knowledge_id: string; name: string; description: string; data_id: string }) =>
      nl2sqlService.updateTerm(data),
    {
      manual: true,
      onSuccess: () => {
        message.success('更新术语成功');
        setIsModalVisible(false);
        resetForm();
        refresh();
      },
      onError: (error) => {
        message.error('更新术语失败');
        console.error('更新术语失败:', error);
      },
    }
  );

  // 删除术语
  const { runAsync: deleteTerm, loading: deleteLoading } = useRequest(
    (data: { knowledge_id: string; name: string; description: string; data_id: string }[]) =>
      nl2sqlService.deleteTerm(data),
    {
      manual: true,
      onSuccess: () => {
        message.success('删除术语成功');
        refresh();
        setSelectedRowKeys([]);
      },
      onError: (error) => {
        message.error('删除术语失败');
        console.error('删除术语失败:', error);
      },
    }
  );

  // 批量删除术语
  const { runAsync: batchDeleteTerms, loading: batchDeleteLoading } = useRequest(
    async () => {
      // const promises = selectedRowKeys.map((key) => {
      //   const term = terms.find((t) => t.data_id === key);
      //   if (term) {
      //     return deleteTerm([{
      //       knowledge_id: term.knowledge_id,
      //       name: term.name,
      //       description: term.description,
      //       data_id: term.data_id!,
      //     }]);
      //   }
      // });
      // await Promise.all(promises);
      // 构建要删除的术语列表
      const termsToDelete = selectedRowKeys
        .map((key) => {
          const term = terms.find((t) => t.data_id === key);
          if (term && term.data_id) {
            return {
              knowledge_id: term.knowledge_id,
              name: term.name,
              description: term.description,
              data_id: term.data_id,
            };
          }
          return null;
        })
        .filter((term): term is { knowledge_id: string; name: string; description: string; data_id: string } =>
          term !== null
        ); // 类型守卫过滤掉 null 值

      if (termsToDelete.length > 0) {
        // 直接调用批量删除接口，传递整个列表
        await deleteTerm(termsToDelete);
      }
    },
    {
      manual: true,
      onSuccess: () => {
        // message.success('批量删除成功');
        setSelectedRowKeys([]);
      },
    }
  );

  // 过滤表格数据
  const filteredTerms = terms.filter((term) => {
    if (!searchValue) return true;
    return (
      term.name.toLowerCase().includes(searchValue.toLowerCase()) ||
      term.description.toLowerCase().includes(searchValue.toLowerCase())
    );
  });

  // 重置表单
  const resetForm = () => {
    setFormData({ name: '', description: '' });
    setEditingTerm(null);
  };

  // 打开新增模态框
  const handleAdd = () => {
    setIsModalVisible(true);
    setEditingTerm(null);
    resetForm();
  };

  // 打开编辑模态框
  const handleEdit = (record: TermInfo) => {
    setEditingTerm(record);
    setFormData({
      name: record.name,
      description: record.description,
    });
    setIsModalVisible(true);
  };

  // 处理删除
  const handleDelete = (record: TermInfo) => {
    if (record.data_id) {
      deleteTerm([{
        knowledge_id: record.knowledge_id,
        name: record.name,
        description: record.description,
        data_id: record.data_id,
      }]);
    }
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的术语');
      return;
    }
    batchDeleteTerms();
  };

  // 处理表单提交
  const handleSubmit = () => {
    if (!formData.name.trim()) {
      message.warning('请输入术语名称');
      return;
    }
    if (!formData.description.trim()) {
      message.warning('请输入术语描述');
      return;
    }

    if (editingTerm) {
      // 更新术语
      if (editingTerm.data_id) {
        updateTerm({
          knowledge_id: editingTerm.knowledge_id,
          name: formData.name.trim(),
          description: formData.description.trim(),
          data_id: editingTerm.data_id,
        });
      }
    } else {
      // 创建术语
      createTerm({
        knowledge_id: knowledgeId,
        name: formData.name.trim(),
        description: formData.description.trim(),
      });
    }
  };

  // 处理模态框关闭
  const handleModalClose = () => {
    setIsModalVisible(false);
    resetForm();
  };

  // 表格列定义
  const columns = [
    {
      title: '术语名称',
      dataIndex: 'name',
      width: 200,
      key: 'name',
      render: (text: string) => (
        <span className="text-blue-600 font-medium">{text}</span>
      ),
    },
    {
      title: '术语描述',
      dataIndex: 'description',
      width: 200,
      key: 'description',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: TermInfo) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            className="text-blue-600 hover:text-blue-800"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个术语吗？"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              size="small"
              icon={<DeleteOutlined />}
              className="text-red-600 hover:text-red-800"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  return (
    <div className="flex-1 flex flex-col">
      {/* 搜索栏 */}
      <div className="mb-4 px-4 pt-4">
        <Search
          placeholder="搜索"
          className="w-full max-w-sm"
          allowClear
          value={searchValue}
          onChange={(e) => setSearchValue(e.target.value)}
        />
      </div>

      {/* 操作按钮 */}
      <div className="mb-4 px-4 flex items-center justify-end">
        <div className="flex items-center gap-2 justify-end mr-2">
          {selectedRowKeys.length > 0 && (
            <>
              {/* <span>
                已选择 {selectedRowKeys.length} 项
              </span> */}
              <Button
                onClick={() => setSelectedRowKeys([])}
                className="text-gray-500"
              >
                取消
              </Button>
              <Popconfirm
                title={`确定要删除选中的 ${selectedRowKeys.length} 个术语吗？`}
                onConfirm={handleBatchDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  danger
                  icon={<DeleteOutlined />}
                  loading={batchDeleteLoading}
                >
                  删除
                </Button>
              </Popconfirm>
            </>
          )}
        </div>
        <Button
          type="secondary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
          className="bg-blue-500 hover:bg-blue-600"
        >
          新增术语
        </Button>
      </div>

      {/* 术语列表 */}
      <div className="flex-1 overflow-hidden px-4">
        <Tables
          columns={columns}
          dataSource={filteredTerms}
          rowKey="data_id"
          loading={loading}
          rowSelection={rowSelection}
          // paginationProps={{
          //   total: filteredTerms.length,
          //   pageSize: 10,
          //   showSizeChanger: true,
          //   showQuickJumper: true,
          // }}
          scroll={{ y: 'calc(100vh - 400px)' }}
        />
      </div>

      {/* 新增/编辑术语模态框 */}
      <Modals
        title={editingTerm ? '编辑术语' : '新增术语'}
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={handleModalClose}
        confirmLoading={createLoading || updateLoading}
        onClose={handleModalClose}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              术语名称
            </label>
            <input
              type="text"
              placeholder="请输入术语名称"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              术语描述
            </label>
            <textarea
              placeholder="请输入术语描述"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              rows={4}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
            />
          </div>
        </div>
      </Modals>
    </div>
  );
};

export default TerminologyManagement; 